#!/usr/bin/env python
# coding=utf-8
#--------------------------------------------------------------------------
# 文件名:       wpLangSend.py 
# 说明：        目的、作用说明
#
# 版本：        0.01
# 作者：        xiao
#
# 创建时间：    2012-01-04 
# 许可证：      Apache License V2.0
#--------------------------------------------------------------------------

import os
import sqlite3DB
import random
import ConfigParser
import WpXMLRPC
import time
import sys
import codecs
import base64
import XiaoTool as xt

## 类注释
#
class wpLangSend:

	## 方法注释
	#
	#  @param
	#  @return
	#
	def __init__(self, confFile="wpLangSend.conf"):
		self.confFile = confFile
		self.path = sys.path[0]
		self.featuresString = {"es":u"características", "de":u"Features", "fr":u"caractéristiques", "it":u"caratteristiche", "nl":u"functies"}
		self.buy = {"es":u"comprar", "de":u"kaufen", "fr":u"Acheter", "it":u"acquistare", "nl":u"kopen"}
		self.conf()
		for lg in self.langs:
			self.send_post(lg)
	#------------------------------------------ End def __init__()

	## 方法注释
	#
	#  @param
	#  @return
	#
	def conf(self):
		confPath = os.path.join(self.path, self.confFile)
		config = ConfigParser.ConfigParser()
		config.readfp(codecs.open(confPath, encoding='UTF-8'))
		
		self.blog_type = config.get("blog", "blog_type")
		self.blog_user_pass = config.get("blog", "blog_user_pass")
		html_tmp = config.get("blog", "html_tmp")
		self.blog_key=config.get("blog", "blog_key")

		self.blog_post_num = int(config.get("send", "blog_post_num"))
		self.point_num = config.get("send", "point_num")

		self.dbname = config.get("init", "dbname")
		self.keyname = config.get("init", "keyname")

		self.langs = config.get("blog", "blog_langs").split()
		self.blog_langs = {}
		for lg in self.langs:
			self.blog_langs[lg] = config.get("blog", "blog_lang_%s" % lg).split()

			if not os.path.isfile(os.path.join(self.path, self.dbname % lg)):
				print(os.path.join(self.path, self.dbname % lg))
				xt.setTimeLog("数据库文件不存在！")
				exit()

			if not os.path.isfile(os.path.join(self.path, self.keyname % lg)):
				xt.setTimeLog("key文件不存在！")
				exit()

		if not os.path.isfile(os.path.join(self.path, html_tmp)):
			html_tmp = "send.html"

		self.tmpStr = codecs.open(os.path.join(self.path, html_tmp), encoding='UTF-8').read()
	#------------------------------------------ End def conf()

	## 方法注释
	#
	#  @param
	#  @return
	#
	def send_post(self, lg="es"):
		f = codecs.open(os.path.join(self.path, self.keyname % lg), encoding='UTF-8')
		keyList = [l.strip() for l in f.readlines()]
		f.close()

		db = sqlite3DB.DbAction(os.path.join(self.path, self.dbname % lg))
		db.dbLoad()
		proSqlQuery = db.query("SELECT id, name, price, features, description, asin FROM `product` WHERE flag=0;")

		for blog_url in self.blog_langs[lg]:
			if random.randint(0, 1):
				continue
			
			time1 = time.time()
			i = 0
			while i < self.blog_post_num and len(proSqlQuery) > 0:
				raid = random.randint(0, len(proSqlQuery) - 1)
				id, name, price, features, description, asin = proSqlQuery.pop(raid)

				fname = codecs.open(os.path.join(self.path, "%s.ini" % blog_url), encoding='UTF-8')
				fnamelist = [l.strip() for l in fname.readlines()]
				fname.close()

				key_name = random.sample(keyList, 1)[0]

				try:
					# 组装发送内容
					title = ""
					asinStr = u"http://www.amazon.com/gp/product/{asin}/ref=as_li_qf_sp_asin_tl?ie=UTF8&tag=tohealth-20&linkCode=as2&camp=217153&creative=399349&creativeASIN={asin}".replace(u"{asin}", asin)
					mt_keywords = []

					# 处理 title
					if random.randint(0, 1):
						title = u"{key} {name}".replace(u"{key}", key_name).replace(u"{name}", name)
					else:
						title = u"{name} {key}".replace(u"{key}", key_name).replace(u"{name}", name)

					title = title.title().replace("&Apos;", "&apos;")

					# 处理属性
					attrsStr = u"""<div class="red">{price}</div><div>{fs}: {ft}</div>""".replace(u"{price}", price).replace(u"{fs}", self.featuresString[lg]).replace(u"{ft}", features)

					docArray = description.split(".")
					ldocArray = len(docArray)
					docraid = random.randint(0, ldocArray - 1)
					docArray[docraid] = u"%s %s" % (title, docArray[docraid])

					if ldocArray > 8:
						docraid = random.randint(0, ldocArray - 1)
						docArray[docraid] += u" %s" % key_name

					des_on = self.tmpStr.replace(u"{name}", name).replace(u"{attrs}", attrsStr).replace(u"{doc}", ".".join(docArray)).replace(u"{url}", asinStr).replace(u"{buy}", self.buy[lg])


					wp = WpXMLRPC.WpXMLRPC("http://%s" % blog_url, random.sample(fnamelist, 1)[0], self.blog_user_pass, self.blog_type)
					title = base64.b64encode(title.encode('UTF-8'))
					des_on = base64.b64encode(des_on.encode('UTF-8'))
					mt_keywords_str = base64.b64encode(key_name.encode('UTF-8'))
					wp.newPost({"title":title, "description":des_on, "mt_keywords":mt_keywords_str})
					db.save("UPDATE `product` SET flag=2 WHERE id=%s;" % id)
					i += 1
				except:
					continue

			xt.setTimeLog("%s 接收日志 %s 篇完毕！TIME：%s" % (blog_url, i, time.time()-time1))

			db.dbClose()
	#------------------------------------------ End def send_post()


#------------------------------------------------------ End class wpLangSend()


if __name__ == "__main__":
	wpLangSend()
